package org.springblade.mes.logistics.loc.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.mes.logistics.area.entity.InventoryArea;
import org.springblade.mes.logistics.loc.entity.InventoryLoc;
import org.springblade.mes.logistics.loc.mapper.InventoryLocMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 库位信息 服务实现类
 *
 * @author 翁金川
 * @since 2025-06-24
 */
@Service
@DS("logistics")
public class InventoryLocService extends BaseServiceImpl<InventoryLocMapper, InventoryLoc> {
    /**
     * 根据编码查询
     *
     * @param area
     * @param tenantId
     * @param ctx
     * @return
     */
    public InventoryLoc refreshByNo(InventoryArea area, String tenantId, Map<String, Object> ctx) {
        String key = "Area_" + area.getAreaCode();
        Object v = ctx.get(key);
        if (v instanceof InventoryLoc) {
            return (InventoryLoc) v;
        }
        InventoryLoc t = null;

        LambdaQueryWrapper<InventoryLoc> lambdaQueryWrapper = Wrappers.lambdaQuery(InventoryLoc.class);
        lambdaQueryWrapper.eq(InventoryLoc::getLocCode, area.getAreaCode()).eq(InventoryLoc::getTenantId, tenantId);
        List<InventoryLoc> dataList = this.list(lambdaQueryWrapper);
        if (dataList != null && dataList.size() > 0) {
            t = dataList.get(0);
        }

        if (t == null) {
            t = new InventoryLoc();
            t.setLocCode(area.getAreaCode());
            t.setLocName(area.getAreaName());
            t.setIsDeleted(0);
            t.setTenantId(tenantId);
            t.setPid(area.getId());
            t.setStatus(0);
            t.setId(null);
            t.setCreateTime(new Date());
            t.setUpdateTime(new Date());
            this.save(t);
        }
        ctx.put(key, t);
        return t;
    }
}
